package com.ktjy.service.impl;

import jakarta.mail.MessagingException;
import jakarta.mail.internet.MimeMessage;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;

import java.io.File;

@Service
public class MailService {
    @Autowired
    JavaMailSender javaMailSender;

    public void send(String from, String to, String title, String content,
                     String fileName, File file, String... cc) throws MessagingException {
        //创建消息对象
        MimeMessage mimeMessage=javaMailSender.createMimeMessage();

//        MimeMessageHelper messageHelper=new MimeMessageHelper(mimeMessage);
        MimeMessageHelper messageHelper=new MimeMessageHelper(mimeMessage,true);
        messageHelper.setFrom(from);//设置发送者
        messageHelper.setTo(to);//设置收件者
        if(!ObjectUtils.isEmpty(cc)){
            messageHelper.setCc(cc);//设置抄送人
        }
        messageHelper.setSubject(title);//设置邮件主题
//        messageHelper.setText(content);//邮件内容
        messageHelper.setText(content,true);//邮件内容
        messageHelper.addAttachment(fileName,file);//传递附件

        javaMailSender.send(mimeMessage);
    }
}
